package com.esm.pdawms.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esm.pdawms.R;
import com.esm.pdawms.adapter.DemoAdapter;
import com.esm.pdawms.database.manager.SystemCenter;
import com.esm.pdawms.model.Hprkcode;
import com.esm.pdawms.model.Pankujl;
import com.esm.pdawms.util.HttpRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.model.Entry;
import zuo.biao.library.util.JSON;

public class PankuActivity extends BaseActivity implements View.OnClickListener, MyReceiver.Message {
    private static final String TAG = "PankuActivity";

    public static Intent createIntent(Context context) {
        return new Intent(context, PankuActivity.class);
    }

    MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_panku);

        initView();
        initData();
        initEvent();

        myReceiver = new MyReceiver();
        myReceiver.message = this;
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.ACTION_DECODE_DATA");
        intentFilter.addAction("com.scanner.broadcast");
        registerReceiver(myReceiver, intentFilter);

        edit_kwcode.setText(SystemCenter.getInstance().esmcode);
        scanKWcode(SystemCenter.getInstance().esmcode);
    }

    public static final int BAOJING = 1819;//报警
    public static final int UPDATEKWDETAIL = 1820;//更新库位详情

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (BAOJING == msg.what) {
                baojing();
            } else if (UPDATEKWDETAIL == msg.what) {
                scanKWcode(_kwbh);
            }
        }
    };

    AssetFileDescriptor afd = null;
    AssetManager am = null;
    //错误扫码报警
    void baojing() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        //这里示例的代码是使用点击按钮的时候可以实现震动，在按钮的点击事件的函数中添加这样几句话
        /*这里使用的是一个长整型数组，数组的a[0]表示静止的时间，a[1]代表的是震动的时间，然后数组的a[2]表示静止的时间，
         * a[3]代表的是震动的时间……依次类推下去，然后这里的代码有一点小小的改变
         */
        long[] patter = {50, 1000};
        vibrator.vibrate(patter, -1);

        //播放声音
        if (am == null) {
            am = getAssets();
            try {
                afd = am.openFd("14184.mp3");
            } catch (IOException e) {

            }
        }
        initMediaPlayer();
    }

    private final MediaPlayer mediaPlayer = new MediaPlayer();
    private void initMediaPlayer() {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ListView lv_hpcode;
    private TextView tv_dqzkinfo;
    private TextView tv_ruku;
    private EditText edit_kwcode;
    private EditText edit_hkcode;

    private EditText edit_hpname;
    private EditText edit_hpcode;
    private EditText edit_pici;

    @Override
    public void initView() {
        lv_hpcode = (ListView) findViewById(R.id.lv_hpcode);

        tv_dqzkinfo = (TextView) findViewById(R.id.tv_dqzkinfo);
        edit_kwcode = (EditText) findViewById(R.id.edit_kwcode);
        edit_hkcode = (EditText) findViewById(R.id.edit_hkcode);
        edit_hpname = (EditText) findViewById(R.id.edit_hpname);
        edit_hpcode = (EditText) findViewById(R.id.edit_hpcode);
        edit_pici = (EditText) findViewById(R.id.edit_pici);
        //禁止响应按键焦点
        lv_hpcode.setFocusable(false);
        reset();
    }

    private void reset() {
        tv_dqzkinfo.setText("");
        edit_kwcode.setText("");
        edit_hkcode.setText("");
        edit_hpname.setText("");
        edit_hpcode.setText("");
        edit_pici.setText("");
        _kwbh = "";
        _hpcode = "";
        SystemCenter.getInstance().hkList.clear();
        updateData();
    }

    private DemoAdapter adapter;

    private void setList(List<Entry<Integer, String>> list) {
        if (list == null) {
            return;
        }
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_hpcode.setAdapter(adapter);
        }
        adapter.refresh(list);
    }

    private List<Entry<Integer, String>> demodataList;

    protected List<Entry<Integer, String>> getList() {
        demodataList = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < SystemCenter.getInstance().hkList.size(); i++) {
            demodataList.add(new Entry<Integer, String>(i, ""));
        }
        return demodataList;
    }

    void updateData() {
        setList(getList());
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 782:
                //扫码按键
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    //库位的货品详情
    void scanKWcode(String kwbh) {
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.kwdetail(kwbh, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    dismissProgressDialog();

                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    } else {
                        showShortToast(getString(R.string.wlwlj));
                        tv_dqzkinfo.setText(getString(R.string.wlwlj));
                        return;
                    }

                    if (code == 1) {
                        String data = jsonObject.getString("data");
                        JSONObject jsonObject2 = JSON.parseObject(data);
                        JSONArray jsonArray = jsonObject2.getJSONArray("list");
                        SystemCenter.getInstance().hkList.clear();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject a = jsonArray.getJSONObject(i);
                            Hprkcode hp = new Hprkcode();
                            hp.setName(a.getString("name"));
                            hp.setHpcode(a.getString("hpcode"));
                            hp.setPh(a.getString("ph"));
                            hp.setNum(a.getInteger("num"));
                            hp.setOnenum(a.getFloat("onenum"));
                            SystemCenter.getInstance().hkList.add(hp);
                        }

                        updateData();
                        if (kwbh.compareToIgnoreCase(_kwbh) == 0) {

                        } else {
                            _kwbh = kwbh;
                            tv_dqzkinfo.setText(R.string.zqdwxm);
                        }
                    } else {
                        mHandler.sendEmptyMessage(BAOJING);
                        String msg = jsonObject.getString("msg");
                        showShortToast(msg);
                        tv_dqzkinfo.setText(msg);
                    }

                }
            });
        } catch (Exception e1) {
            showShortToast(getString(R.string.wlwlj));
            tv_dqzkinfo.setText(getString(R.string.wlwlj));
            dismissProgressDialog();
        }
    }

    String _kwbh = "";//正确的库位码
    String _hpcode = "";
    @Override
    public void getMsg(String str) {
        //通过实现MyReceiver.Message接口可以在这里对MyReceiver中的数据进行处理
        showShortToast(str);
        if (_kwbh.isEmpty()) {
            //先扫库位
            scanKWcode(str);
            edit_kwcode.setText(str);
        } else if (_kwbh.compareToIgnoreCase(str) == 0) {
            return;
        }
        //禁止响应按键焦点
        lv_hpcode.setFocusable(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

}